<!--
 * @Descripttion: 多张图片上传
 * @Author: 刘黎
 * @Date: 2024-04-07 17:00:50
 * @LastEditors: 刘黎
 * @LastEditTime: 2024-08-19 01:10:48
-->
<template>
  <div class="fileBox">
    <div class="fileData">
      <div v-for="list,index of fileList" :key="index"
        draggable="true"
        @dragstart="dragStart($event,index)"
        @dragenter="dragEnter($event,index)"
        @dragend="dragEnd"
        class="list"
      >
        <div class="tipsOption">
          <el-icon class="moreBut" @click="moreClickFun(list)"><Search /></el-icon>
          <el-icon class="deteleBut" @click="deteleFun(list, index)"><DeleteFilled /></el-icon>
        </div>
        <template v-if="list.url.includes('mp4')">
          <video :src="list.url" :second="3" />
        </template>
        <el-image v-else :src="list.url"></el-image>
      </div>
    </div>
    <el-upload
      ref="uploadRef"
      action="#"
      :show-file-list="false"
      :auto-upload="false"
      :accept="props.accept"
      :limit="props.limit"
      list-type="picture-card"
      multiple
      :on-change="handleChange"
    >
      <el-icon><Plus /></el-icon>
    </el-upload>
    <el-dialog v-model="dialogVisible" top="5vh">
      <template v-if="currentPreviewSrc.includes('mp4')">
        <!-- <video :src="currentPreviewSrc" /> -->
        <video controls="" width="640" height="427" :src="currentPreviewSrc"></video>
      </template>
      <el-image
        v-else
        style="display: block; max-width: 100%;"
        :src="currentPreviewSrc"
        :preview-src-list="[currentPreviewSrc]"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { computed,ref,onMounted,watch } from 'vue';
import { postApi } from "@/api/api"
import { ElLoading } from 'element-plus'
import { ElMessageBox, ElMessage } from 'element-plus'

const props = defineProps({
  fileUploadList: [Array, String],
  limit: 50,
  accept: '.jpg,.png'
})
const emit = defineEmits(['getImagesFun'])
let fileList = ref([])

// console.log(props.fileUploadList)
// watch(props.fileUploadList, (newValue, oldValue) => {
//   console.log(props.fileUploadList)
//   console.log(newValue)
//   console.log(oldValue)
//   // 这里可以执行需要的函数
//   fileList.value = props.fileUploadList || []
// });
watch(() => props.fileUploadList, (newValue, oldValue) => {
  // 这里可以执行需要的函数
  fileList.value = props.fileUploadList || []
});

 //上传图片
function handleChange(file) {
  var files
  console.log(file)
  if (file.raw.size < 1024 * 1024 * 200 ) {
    files = file.raw
    if (files.size > 0) {
      const loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading'
      })
      let ossData = new FormData()
      // ossData.append('name', files.name)
      ossData.append('file', files)
      console.log(fileList.value)
      postApi('/ajax/upload', ossData).then(res => {
        loading.close()
        if(res.data.url.includes('mp4')){
          let temp = {
            uid: files.uid,
            name: files.name,
            url: res.data.url
          }
          fileList.value.splice(1, 0, temp);
        }else{
          fileList.value.push({
            uid: files.uid,
            name: files.name,
            url: res.data.url
          })
        }
        
        console.log(fileList.value)
        // fileList.value.sort((a, b) => {
        //   // 提取name属性中的第一个字符
        //   let numA = parseInt(a.name.charAt(0), 10);
        //   let numB = parseInt(b.name.charAt(0), 10);
          
        //   // 比较数字大小
        //   if (numA < numB) {
        //       return -1;
        //   }
        //   if (numA > numB) {
        //       return 1;
        //   }
        //   return 0;
        // });
        // console.log('排序后', fileList.value);
        // let arr = [
        //   {name: '2apple',url:'xx'},
        //   {name: '1banana',url:'xx'},
        //   {name: '10cherry',url:'xx'},
        //   {name: '2date',url:'xx'},
        //   {name: '3elderberry',url:'xx'},
        //   {name: 'aaa',url:'xx'}
        // ];
        
        fileList.value.sort((a, b) => {
          let nameA = a.name;
          let nameB = b.name;

          // 尝试将名字的首字符转换为数字
          let numA = Number(nameA[0]);
          let numB = Number(nameB[0]);

          // 检查转换是否成功，并进行数字比较
          if (!isNaN(numA) && !isNaN(numB)) {
              if (numA < numB) {
                  return -1;
              }
              if (numA > numB) {
                  return 1;
              }
          }

          // 转换失败，或数字相同，使用字符串比较
          return nameA.toUpperCase().localeCompare(nameB.toUpperCase());
        });

        console.log(fileList.value);
        emit("getImagesFun", fileList.value)
      }).catch(() => {
        loading.close()
      })
    } else {
      ElMessage({message: "不能上传空文件",type: 'error'})
    }
  }else{
    ElMessage({message: "不能上传大于200M文件",type: 'error'})
    reject(false)
  }
}
let dialogVisible = ref(false)
let currentPreviewSrc = ref('')
// 预览图片
function moreClickFun(list) {
  dialogVisible.value = true
  currentPreviewSrc.value = list.url
}
let uploadRef = ref('')
// 删除图片
function deteleFun(list, index) {
  fileList.value.splice(index, 1)
  emit("getImagesFun", fileList.value)
}

// 当前被拖拽的元素索引
let draggingIndex = ref(-1);

// 拖拽开始时的处理函数
const dragStart = (event, index) => {
  console.log('拖拽开始时的处理函数', index)
  draggingIndex.value = index;
};

// 拖拽过程中的处理函数
const dragEnter = (event, index) => {
  console.log('拖拽过程中的处理函数', index)
 if (draggingIndex.value !== index) {
  console.log('拖拽过程中的处理函数222222222222222')
    const source = fileList.value[draggingIndex.value];
    fileList.value.splice(draggingIndex.value, 1);
    fileList.value.splice(index, 0, source);
    draggingIndex.value = index;
    console.log(fileList.value)
 }
};

// 拖拽结束时的处理函数
const dragEnd = () => {
  console.log('拖拽结束时的处理函数')
  draggingIndex.value = -1;
}

onMounted(()=>{
  console.log(props.fileUploadList)
  fileList.value = props.fileUploadList || []
})
</script>

<style lang="scss" scoped>
.fileBox{
 display: flex;
 flex-wrap: wrap;
}
.fileData{
  display: flex;
  flex-wrap: wrap;
  .list{
    position: relative;
    margin-right: 10px;
    margin-bottom: 10px;
    width: 148px;
    height: 148px;
    .el-image{
      width: 148px;
      height: 148px;
    }
    video{
      width: 148px;
      height: 148px;
    }
    .tipsOption{
      position: absolute;
      top: 0%;
      left: 0%;
      width: 100%;
      height: 100%;
      padding: 0 40px;
      font-size: 20px;
      z-index: 9;
      color: #fff;
      background: rgba(0, 0, 0 , .3);
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      opacity: 0;
    }
    .moreBut{
      cursor: pointer;
    }
    .deteleBut{
      cursor: pointer;
    }
  }
  .list:hover{
    .tipsOption{
      opacity: 1;
    }
  }
  .list:active {
    cursor: grabbing; /* 拖动手势 */
  }
}
</style>
